import axios from 'axios'
import { localCache } from '@/utils/cache'
import { uniqueRequsets } from '@/utils/uniqueRequsets'
import emitter from '@/emitter'
import { api_fail, api_invalid, api_un_auth, api_success } from '@/emitter'

const { VITE_APP_API_BASE_URL, VITE_API_TIMEOUT } = import.meta.env
const { addPendingRequest, removePendingRequest } = uniqueRequsets()

const request = axios.create({
  baseURL: VITE_APP_API_BASE_URL,
  timeout: VITE_API_TIMEOUT
})

/**
 * 全局请求拦截器
 */
request.interceptors.request.use(
  (config) => {
    // 添加请求拦截器
    addPendingRequest(config)
    const token = localCache.get('TOKEN')
    if (config.headers && token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    // window.$msgTip(error.message, MsgEnum.error)
    emitter.emit(api_fail, error.message)
    return Promise.reject(error)
  }
)

/**
 * 全局响应拦截器
 */
request.interceptors.response.use(
  (response) => {
    // 移除请求拦截器
    removePendingRequest(response)

    const url = response.config.url

    emitter.emit(api_success, url)
    return response.data
  },
  (error) => {
    const { status, statusText } = error.response
    const message = error.response.data.message
    if (status === 400) {
      emitter.emit(api_invalid, statusText, message, status)
    } else if (status === 401) {
      emitter.emit(api_un_auth, statusText, message, status)
    } else {
      emitter.emit(api_fail, statusText, message, status)
    }
    // let msg = ''
    // const status = error.response.status
    // switch (status) {
    //   case 400:
    //     msg = '请求错误!'
    //     break
    //   case 401:
    //     msg = '未授权，请登录!'
    //     break
    //   case 403:
    //     msg = '拒绝访问!'
    //     break
    //   case 404:
    //     msg = `请求地址出错: ${error.response.config.url}`
    //     break
    //   default:
    //     msg = '请求超时或网络异常，请检查网络设置'
    //     break
    // }
    return Promise.reject(error)
  }
)
export default request
